<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class TaskRecords extends AdminController
{
    public $_validation = null;

    function __construct(){
        parent::__construct();
        $this->_validation = Array(
            array('field' => 'task_id', 'label' => '任务', 'rules' => 'required|integer|max_length[11]')
        , array('field' => 'pay_request_id', 'label' => '所属财务申请记录', 'rules' => 'integer|max_length[11]')
        , array('field' => 'operator_id', 'label' => '接单者', 'rules' => 'required|integer|max_length[11]')
        , array('field' => 'true_product_price', 'label' => '实际购买时商品价格', 'rules' => 'numeric')
        , array('field' => 'buyer_pay_total', 'label' => '买手下单支付的钱数', 'rules' => 'numeric')
        , array('field' => 'buyer_pay_coin_type', 'label' => '买手下单付的币种', 'rules' => 'trim|integer|max_length[4]')
        , array('field' => 'order_no', 'label' => '买家下单号', 'rules' => 'required|trim|exact_length[19]')
        , array('field' => 'comment_link', 'label' => '评论链接', 'rules' => 'trim|max_length[512]')
        , array('field' => 'buyer_order_time', 'label' => '买家下单时间', 'rules' => 'max_length[32]')
        , array('field' => 'buyer_pay_time', 'label' => '买手下单付款日期', 'rules' => 'max_length[32]')
        , array('field' => 'add_image', 'label' => '付款截图', 'rules' => '')
        , array('field' => 'add_image_1', 'label' => '付款截图1', 'rules' => '')
        , array('field' => 'add_image_2', 'label' => '附加截图2', 'rules' => '')
        , array('field' => 'ceping_type', 'label' => '测评类型', 'rules' => 'integer')
        , array('field' => 'remark', 'label' => '备注', 'rules' => '')
        , array('field' => 'update_time', 'label' => '更新时间', 'rules' => '')
        );

        $this->load->model('MTaskRecords');
        $this->load->model('MAdmin');
        $this->load->model('MAdminGroup');
        $this->load->model('MShop');
        $allReviewsAdmin = $this->MAdmin->getAllReviewsAdmin();//所有测评人,包含销售组成员，也可以作为测试人
        $allSaleGroups = MAdminGroup::getAllGroupsByType(1);//所有销售组
        $allReviewsGroups = MAdminGroup::getAllGroupsByType(2);//所有测评组
        $allShops = $this->MShop->getAllShopsTrue();
        $allFanaceAdmin = $this->MAdmin->getAllFanceAdmin();//所有财务人员
        $this->assign('allReviewsAdmin', $allReviewsAdmin);
        $this->assign('allSaleGroups', $allSaleGroups);
        $this->assign('allReviewsGroups', $allReviewsGroups);
        $this->assign('allShops', $allShops);
        $this->assign('allFanaceAdmin', $allFanaceAdmin);
    }

    function index(){
        //$this->output->enable_profiler(TRUE);
        $this->load->library('FormFilter');
        $this->load->helper('formfilter');
        $this->formfilter->addFilter('tr.task_id', 'where');
        $this->formfilter->addFilter('tr.operator_id', 'where');
        $this->formfilter->addFilter('t.country', 'where');
        $this->formfilter->addFilter('t.group_id', 'where');
        $this->formfilter->addFilter('t.shop_id', 'where');
        $this->formfilter->addFilter('tr.contact', 'where');
        $this->formfilter->addFilter('tr.order_no', 'where');
        $this->formfilter->addFilter('tr.status', 'where');
        $this->formfilter->addFilter('tr.payment_type', 'where');
        $this->formfilter->addFilter('tr.pay_method', 'where');

        if ($begintime = filterValue('task_records_create_time_begin')) {
            $this->formfilter->addFilter('task_records_create_time_begin', 'where', array('tr.create_time >= ', strtotime($begintime . ' 00:00:00')));
        }
        if ($endtime = filterValue('task_records_create_time_end')) {
            $this->formfilter->addFilter('task_records_create_time_end', 'where', array('tr.create_time <= ', strtotime($endtime . ' 23:59:59')));
        }

        if ($beginupdatetime = filterValue('task_records_update_time_begin')) {
            $this->formfilter->addFilter('task_records_update_time_begin', 'where', array('tr.update_time >= ', strtotime($beginupdatetime . ' 00:00:00')));
        }
        if ($endupdatetime = filterValue('task_records_update_time_end')) {
            $this->formfilter->addFilter('task_records_update_time_end', 'where', array('tr.update_time <= ', strtotime($endupdatetime . ' 23:59:59')));
        }

        $number_perpage = filterValue('taskrecords_number_perpage');
        $total_number = $this->MTaskRecords->getCount();
        $limit = $this->pagination($total_number, '', $number_perpage);
        $list = $this->MTaskRecords->getList($limit);
        $this->assign('total_number', $total_number);
        $this->assign('list', $list);
        $this->layout();
    }

    function add($task_id){
        if (!is_numeric($task_id)) {
            show_error(l('id_not_null'));
        }
        $post = $this->input->post();
        //得到task_id详情
        $this->load->model('MTask');
        $this->load->model('MTaskRecordItem');
        $task_info = $this->MTask->getById($task_id);
        $obj = $this->MTaskRecords->createVo();
        $obj->task_id = $task_id;
        $obj->asin = $task_info->asin;
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);

        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            $newObj->asin = $task_info->asin;
            $newObj->buyer_order_time = strtotime($newObj->buyer_order_time);
            $newObj->buyer_pay_time = strtotime($newObj->buyer_pay_time);
            $newObj->review_time = strtotime($newObj->review_time);

            //粘贴的图片
            if (!file_exists('upload/parseimg/')) {
                if (!mkdir('upload/parseimg/', DIR_WRITE_MODE, true)) {
                    echo json_encode(Array('error' => 'upload/parseimg/'));
                    return;
                }
            }
            if ($this->input->post('add_image')) {
                $add_image = $this->input->post('add_image');
                if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $add_image, $result)) {
                    $type = $result[2];
                    $new_file = "upload/parseimg/" . md5(uniqid(time()) . uniqid(time())) . ".{$type}";
                    file_put_contents($new_file, base64_decode(str_replace($result[1], '', $add_image)));
                }
                $newObj->add_image = $new_file;
            }

            if ($this->input->post('add_image_1')) {
                $add_image_1 = $this->input->post('add_image_1');
                if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $add_image_1, $result1)) {
                    $type1 = $result1[2];

                    $new_file1 = "upload/parseimg/" . md5(uniqid(time()) . uniqid(time())) . ".{$type1}";
                    file_put_contents($new_file1, base64_decode(str_replace($result1[1], '', $add_image_1)));
                }
                $newObj->add_image_1 = $new_file1;
            }

            $this->db->trans_start();
            //查询当前task_id,order_no下是否系统中已有
            $oldRecordInfo = $this->MTaskRecords->getOne(
                array(
                    'task_id' => $newObj->task_id,
                    'order_no' => $newObj->order_no
                )
            );
            $record_id = null;
            if ($oldRecordInfo) {   //原来已有
                //判断原来接单者是不是本人，如果不是本人则给出提示不能修改
                if($oldRecordInfo->operator_id != $newObj->operator_id){
                    errorAndRedirect('编号：'.$oldRecordInfo->operator_id.'已经创建了该单子了，请核查是不是重复录入了！');
                }
                $oldRecordInfo->comment_link = $newObj->comment_link;
                $oldRecordInfo->true_product_price = $newObj->true_product_price;
                $oldRecordInfo->buyer_pay_total = $newObj->buyer_pay_total;
                $oldRecordInfo->buyer_pay_coin_type = $newObj->buyer_pay_coin_type;
                $oldRecordInfo->ceping_type = $newObj->ceping_type;
                $oldRecordInfo->buyer_order_time = $newObj->buyer_order_time;
                $oldRecordInfo->buyer_pay_time = $newObj->buyer_pay_time;
                $oldRecordInfo->review_time = $newObj->review_time;
                $oldRecordInfo->remark = $newObj->remark;
                $oldRecordInfo->asin = $task_info->asin;
                if($newObj->add_image){
                    $oldRecordInfo->add_image = $newObj->add_image;
                }
                if($newObj->add_image_1){
                    $oldRecordInfo->add_image_1 = $newObj->add_image_1;
                }

                // 更新测评类型后更新已接测评量和已完成测评量
                if ($newObj->ceping_type !== $oldRecordInfo->ceping_type){
                    // 添加成功更新已录测评数量
                    $this->load->model('MTaskApplyNum');
                    if (!$this->MTaskApplyNum->updateCepingRecordsCount($newObj->task_id, $newObj->operator_id)) {
                        $this->db->_trans_status = FALSE;
                    }
                    //更新task表中测评/销量数
                    if (!$this->MTask->updateCepingRecordsCount($newObj->task_id)) {
                        $this->db->_trans_status = FALSE;
                    }
                }


                $record_id = $oldRecordInfo->id;
                //0:初始待提交财务，1，财务待处理，2，财务标定异常，3，财务已处理打款
                //进行修改record操作前，先判断是否当前record下的item是否有财务标记异常的，如果有，可以修改record,说明财务已经进行标记异常，可以让修改了。
                //或者所有item的状态中都没有状态是财务 已经完成付款的，也可以进行record的修改动作，只要财务标定完成的，record就不能改，需要联系财务了

                $items = $this->MTaskRecordItem->getAll(array('record_id'=>$record_id));
                $item_status = array();
                foreach ($items as $item){
                    $item_status[] = $item->status;
                }
                if(in_array(2,$item_status) || !in_array(3,$item_status)){
                    $this->MTaskRecords->update($oldRecordInfo);
                }

            }else {
                $record_id = $this->MTaskRecords->add($newObj);
                if(!$record_id){
                    $this->db->_trans_status = FALSE;
                }
            }
            // 添加成功更新已录测评数量
            $this->load->model('MTaskApplyNum');
            if (!$this->MTaskApplyNum->updateCepingRecordsCount($newObj->task_id, $newObj->operator_id)) {
                $this->db->_trans_status = FALSE;
            }
            //更新task表中测评/销量数
            if (!$this->MTask->updateCepingRecordsCount($newObj->task_id)) {
                $this->db->_trans_status = FALSE;
            }
            //货款
            $current_time = time();
            if($post['amount_1']){
                //先查询是否有对应该记录的货款款项记录
                $old_item_1 = $this->MTaskRecordItem->getOne(array('record_id'=>$record_id,'payment_type'=>1));
                if($old_item_1){    //有老的货款记录
                    if($old_item_1->status < 3){    //3=>财务已经处理打款，状态3不能修改了
                        $old_item_1->pay_method = $post['pay_method_1'];
                        $old_item_1->contact = $post['contact_1'];
                        $old_item_1->pay_account = $post['pay_account_1'];
                        $old_item_1->bank = $post['bank_1'];
                        $old_item_1->amount = $post['amount_1'];
                        $old_item_1->coin_type = $post['coin_type_1'];
                        $old_item_1->rate_rmb = $post['rate_rmb_1'];
                        $old_item_1->remark = $post['remark_1'];
                        $old_item_1->update_time = $current_time;
                        if(!$this->MTaskRecordItem->update($old_item_1)){
                            $this->db->_trans_status = FALSE;
                        }
                    }
                }else {  //创建新的记录
                    $item_1 = $this->MTaskRecordItem->createVo();
                    $item_1->record_id = $record_id;
                    $item_1->payment_type = 1;
                    $item_1->pay_method = $post['pay_method_1'];
                    $item_1->contact = $post['contact_1'];
                    $item_1->pay_account = $post['pay_account_1'];
                    $item_1->bank = $post['bank_1'];
                    $item_1->amount = $post['amount_1'];
                    $item_1->coin_type = $post['coin_type_1'];
                    $item_1->rate_rmb = $post['rate_rmb_1'];
                    $item_1->remark = $post['remark_1'];
                    $item_1->status = 0;
                    $item_1->create_time = $current_time;
                    $item_1->update_time = $current_time;
                    if(!$this->MTaskRecordItem->add($item_1)){
                        $this->db->_trans_status = FALSE;
                    }
                }
            }
            //买家佣金
            if($post['amount_2']){
                //先查询是否有对应该记录的买家佣金款项记录
                $old_item_2 = $this->MTaskRecordItem->getOne(array('record_id'=>$record_id,'payment_type'=>2));
                if($old_item_2){    //有老的记录
                    if($old_item_2->status < 3){    //3=>财务已经处理打款，状态3不能修改了
                        $old_item_2->pay_method = $post['pay_method_2'];
                        $old_item_2->contact = $post['contact_2'];
                        $old_item_2->pay_account = $post['pay_account_2'];
                        $old_item_2->bank = $post['bank_2'];
                        $old_item_2->amount = $post['amount_2'];
                        $old_item_2->coin_type = $post['coin_type_2'];
                        $old_item_2->rate_rmb = $post['rate_rmb_2'];
                        $old_item_2->remark = $post['remark_2'];
                        $old_item_2->update_time = $current_time;
                        if(!$this->MTaskRecordItem->update($old_item_2)){
                            $this->db->_trans_status = FALSE;
                        }
                    }
                }else {  //创建新的记录
                    $item_2 = $this->MTaskRecordItem->createVo();
                    $item_2->record_id = $record_id;
                    $item_2->payment_type = 2;
                    $item_2->pay_method = $post['pay_method_2'];
                    $item_2->contact = $post['contact_2'];
                    $item_2->pay_account = $post['pay_account_2'];
                    $item_2->bank = $post['bank_2'];
                    $item_2->amount = $post['amount_2'];
                    $item_2->coin_type = $post['coin_type_2'];
                    $item_2->rate_rmb = $post['rate_rmb_2'];
                    $item_2->remark = $post['remark_2'];
                    $item_2->status = 0;
                    $item_2->create_time = $current_time;
                    $item_2->update_time = $current_time;
                    if(!$this->MTaskRecordItem->add($item_2)){
                        $this->db->_trans_status = FALSE;
                    }
                }
            }
            //中介佣金
            if($post['amount_3']){
                //先查询是否有对应该记录的中介佣金款项记录
                $old_item_3 = $this->MTaskRecordItem->getOne(array('record_id'=>$record_id,'payment_type'=>3));
                if($old_item_3){    //有老的记录
                    if($old_item_3->status < 3){    //3=>财务已经处理打款，状态3不能修改了
                        $old_item_3->pay_method = $post['pay_method_3'];
                        $old_item_3->contact = $post['contact_3'];
                        $old_item_3->pay_account = $post['pay_account_3'];
                        $old_item_3->bank = $post['bank_3'];
                        $old_item_3->amount = $post['amount_3'];
                        $old_item_3->coin_type = $post['coin_type_3'];
                        $old_item_3->rate_rmb = $post['rate_rmb_3'];
                        $old_item_3->remark = $post['remark_3'];
                        $old_item_3->update_time = $current_time;
                        if(!$this->MTaskRecordItem->update($old_item_3)){
                            $this->db->_trans_status = FALSE;
                        }
                    }
                }else {  //创建新的记录
                    $item_3 = $this->MTaskRecordItem->createVo();
                    $item_3->record_id = $record_id;
                    $item_3->payment_type = 3;
                    $item_3->pay_method = $post['pay_method_3'];
                    $item_3->contact = $post['contact_3'];
                    $item_3->pay_account = $post['pay_account_3'];
                    $item_3->bank = $post['bank_3'];
                    $item_3->amount = $post['amount_3'];
                    $item_3->coin_type = $post['coin_type_3'];
                    $item_3->rate_rmb = $post['rate_rmb_3'];
                    $item_3->remark = $post['remark_3'];
                    $item_3->status = 0;
                    $item_3->create_time = $current_time;
                    $item_3->update_time = $current_time;
                    if(!$this->MTaskRecordItem->add($item_3)){
                        $this->db->_trans_status = FALSE;
                    }
                }
            }
            $this->db->trans_complete();
            if ($this->db->trans_status() !== FALSE) {
                successAndRedirect(l('edit_success'), site_url('/tasks/task/view/' . $task_id));
            } else {
                errorAndRedirect(l('data_fail'));
            }
        }
        $this->assign('obj', $obj);
        $this->assign('task_info', $task_info);
        $this->layout();
    }

    function edit($id)
    {
        show_error('修改请到录入任务处填写单号进行修改');
    }

    function delete($id, $update_time)
    {
        if (!is_numeric($id) || !is_numeric($update_time)) {
            show_error(l('id_not_null'));
        }
        if (!$this->MTaskOperate->delete($id, $update_time)) {
            errorAndRedirect(l('data_fail'));
        }
        successAndRedirect(l('delete_success'));
    }

    /**
     * ajax 添加指定任务id的任务操作数据
     * @param $id
     */
    function ajaxAddTaskOperate($task_id)
    {
        if (!$this->p->add) {
            //权限不足
            model_error(l('user_has_nopower'));
        }
        if (((int)$task_id) . '' !== $task_id) {
            model_error(l('id_or_updated_not_null'));
        }
        $this->load->model('MTask');
        if (!$task = $this->MTask->getById((int)$task_id)) {
            model_error('当前任务不存在！');
        }

        $obj = $this->MTaskOperate->createVo();
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);

        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            //检查是否为新客户：客户联系方式在以往测评操作记录中已经存在过算老用户，否则为新用户
            $findObj = $this->MTaskOperate->getOne(array('contact' => $newObj->contact));
            if ($findObj) {
                $newObj->is_new = 2;
            } else {
                $newObj->is_new = 1;
            }
            $newObj->order_time = strtotime($newObj->order_time);
            $newObj->pay_time = strtotime($newObj->pay_time);
            //事务添加任务操作，并修改任务表状态为已接
            $this->db->trans_start();
            if (!$this->MTaskOperate->add($newObj)) {
                $this->db->_trans_status = FALSE;
            }

            if ($task->status == MTask::STATE_NOT_ACCEPT) {
                $task->status = MTask::STATE_ACCEPTED;
                if (!$this->MTask->update($task)) {
                    $this->db->_trans_status = FALSE;
                }
            }

            $this->db->trans_complete();
            if ($this->db->trans_status() !== FALSE) {
                model_success('添加任务操作成功！');
            } else {
                model_error('添加任务操作失败！');
            }
        }

        $this->assign('obj', $obj);
        $this->assign('task', $task);
        $this->assign('thisControllerName', '添加任务操作记录');
        $this->assign('action', 'add');
        $this->layout_modal('modal-form');
    }

    /**
     * ajax 修改指定任务id的任务操作数据
     * @param unknown $id
     */
    function ajaxEditTaskOperate($task_operate_id)
    {
        if (!$this->p->add) {
            //权限不足
            model_error(l('user_has_nopower'));
        }
        if (!is_numeric($task_operate_id)) {
            show_error(l('id_not_null'));
        }
        $obj = $this->MTaskOperate->getOne(Array('id' => $task_operate_id));
        if (!$obj) {
            model_error('未找到定义！');
        }
        $this->load->model('MTask');
        if (!$task = $this->MTask->getById((int)$obj->task_id)) {
            model_error('当前任务不存在！');
        }
        $this->editObj = $obj;

        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);

        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            //检查是否为新客户：客户联系方式在以往测评操作记录中已经存在过算老用户，否则为新用户
            $findObj = $this->MTaskOperate->getOne(array('contact' => $newObj->contact));
            if ($findObj) {
                $newObj->is_new = 2;
            } else {
                $newObj->is_new = 1;
            }
            $newObj->order_time = strtotime($newObj->order_time);
            $newObj->pay_time = strtotime($newObj->pay_time);

            //事务添加任务操作，并修改任务表状态为已接
            if (!$this->MTaskOperate->update($newObj)) {
                $this->db->_trans_status = FALSE;
            }
            $task->status = MTask::STATE_ACCEPTED;
            if (!$this->MTask->update($task)) {
                $this->db->_trans_status = FALSE;
            }
            $this->db->trans_complete();
            if ($this->db->trans_status() !== FALSE) {
                model_success('修改任务操作成功！');
            } else {
                model_error('修改任务操作失败！');
            }
        }

        $this->assign('obj', $obj);
        $this->assign('task', $task);
        $this->assign('thisControllerName', '修改任务操作记录');
        $this->assign('action', 'edit');
        $this->layout_modal('modal-form');
    }

    /**
     * ajax 查找给定id的任务操作详情
     * @param $id
     */
    function ajaxViewDetail($id)
    {
        if (((int)$id) . '' !== $id) {
            model_error(l('id_or_updated_not_null'));
        }
        if (!$obj = $this->MTaskRecords->getById((int)$id)) {
            model_error('任务操作记录不存在！');
        }

        //查询当前测评记录所有款项记录
        $this->load->model('MTaskRecordItem');
        $recordsItems = $this->MTaskRecordItem->getAll(array('record_id'=>$id));

        $this->assign('obj', $obj);
        $this->assign('recordsItems', $recordsItems);
        $this->assign('thisControllerName', '测评记录详情');
        $this->layout_modal('modal-detail');
    }

    /**
     * ajax 请求给定order_no和task_id的record记录和record_item款项记录
     */
    public function ajaxReturnByTaskIdAndOrderNo() {
        $task_id = $this->input->post('task_id');
        $order_no = $this->input->post('order_no');
        $asin = $this->input->post('asin');
        $retObj = array();
        $item_infos = null;
        //锁定当前task_id,order_no,asin的records
        $record_info = $this->MTaskRecords->getOne(array('task_id'=>$task_id,'order_no'=>$order_no,'asin'=>$asin));
        //查询当前记录对应的item款项记录
        if($record_info){
            $this->load->model('MTaskRecordItem');
            $item_infos = $this->MTaskRecordItem->getAll(array('record_id'=>$record_info->id));
        }
        $retObj['recordInfo'] = $record_info;
        $retObj['itemInfos'] = $item_infos;
        exit(json_encode($retObj));
    }


    public function group_cepings()
    {
        $this->load->model('MTaskOperate');
        $data = $this->input->post();

        $ceping_ids = $data['ceping_ids'];
        $cepings = $this->MTaskOperate->getAllByCepingId($ceping_ids);

        //根据测评记录状态判断是否可以合并打款
        $statuses = $cepings['statuses'];
        if (count(array_unique($statuses)) != 1 || (!in_array(2, array_unique($statuses)) && !in_array(0, array_unique($statuses)))) {
            exit(json_encode([
                'status' => 0,
                'msg' => '所选测评记录中含有已被拒绝的记录或无效记录，请检查后重新提交！'
            ]));
        }
        //判断已经可以合并打款后，将ids保存到session中
        $this->session->set_userdata('PAY_REQUEST_CEPING_IDS', $ceping_ids);

        exit(json_encode([
            'status' => 1,
            'msg' => '合并成功',
        ]));
    }

    public function importExcel()
    {
        $this->load->model('MTaskOperate');
        $this->load->model('MTask');
        $this->load->model('MTaskApplyNum');
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/IOFactory');
        $file = $_FILES ['file'] ['tmp_name']; //临时文件
        $file_type = pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
        $operator_id = $this->input->post('operator_id');
        if($file_type=='xlsx' ){
            $objReader = IOFactory::createReader('Excel2007');
        }else{
            $objReader =IOFactory::createReader('Excel5');
        }
        $objPHPExcel = $objReader->load($file);

        //获取sheet表格数目
        $sheetCount = $objPHPExcel->getSheetCount();

        //默认选中sheet0表
        $sheetSelected = 0;
        $objPHPExcel->setActiveSheetIndex($sheetSelected);

        //获取表格列数
        $columnCount = $objPHPExcel->getActiveSheet()->getHighestColumn();

        //验证导入表格格式
        if ($columnCount !== 'AA'){
            echo '请导出正确格式的表格！（由系统提供的表格样式）.<br>';
            echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
            exit();
        }

        $new = $objPHPExcel->getActiveSheet()->toArray();

        if (count($new) == 1){
            echo '没有填数据，你导入个毛线';
            echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
            exit();
        }
        echo "<div>Sheet 数量 : ".$sheetCount."　　行数： ".(count($new)-1)."　　列数：".$columnCount."</div>";
        $unique = array();
        unset($new[0]);
        foreach ($new as $v){
            $v[0] = trim($v[0]);
            $v[2] = trim($v[2]);
            $v[3] = trim($v[3]);
            $unique[] = $v[0].$v[2].$v[3];
            echo '数据校检中...<br>';
        }
        if (count(array_unique($unique)) !== count($unique)){
            echo '数据存在相同任务下相同订单号相同打款类型的数据，检查后重新上传！';
            echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
            exit();
        }

        $this->db->trans_start();
        foreach ($new as $k => $v){
            $v[0] = trim($v[0]);
            $v[2] = trim($v[2]);
            $v[3] = trim($v[3]);
            //验证必填信息是否完整
            if (!$v[0] ||  !$v[1] || !$v[2] || !$v[3] ||!in_array($v[3],[1,2,3,4,5,6,7,8,9]) || !$v[13]){
                echo '第'.$k.'条数据中，请填写任务ID、任务名称、订单号、付款类型、本记录付款方式！';
                echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                exit();
            }

            //查看是否有当前任务的录入测评权限
            $auth = $this->MTaskApplyNum->getAll(['task_id' => $v[0],'operator_id' => $operator_id]);
            if (!$auth){
                echo '第'.$k.'条数据暂无 - <i style="color: #da32ff;">' .$v[1].'</i> - 录入权限，请先去接取该任务！';
                echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                exit();
            }

            //验证数据库中是否含有当前相同记录
            $old = $this->MTaskOperate->getAll(['order_no' => $v[2],'task_id' => $v[0],'operator_id' => $operator_id,'payment_type' => $v[3],'status <>' => 4]);
            if ($old){
                echo '第'.$k.'条数据与该任务下已有测评记录重复或冲突，检查后重新上传！';
                echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                exit();
            }

            //赋值
            $obj = $this->MTaskOperate->createVo();
            $obj->order_no = $v[2];
            $obj->operator_id = $operator_id;
            $obj->task_id = $v[0];
            $obj->payment_type = $v[3];
            $obj->pay_method = $v[13];
            $obj->yunfei = $v[6];
            $obj->buyer_order_time = strtotime($v[11]);
            $obj->buyer_pay_time = strtotime($v[12]);
            $obj->comment_link = $v[4];
            $obj->ceping_type = $v[25];
            $obj->remark = $v[26];
            $obj->contact = $v[15];
            $obj->intror_contact = $v[21];

            foreach ($v as $i_k => $i_value){
                if (!$i_value){
                    if (empty($i_value) && strlen($i_value)){
                        $v[$i_k] = true;
                    }
                }
            }

            //验证录入数据格式与打款类型是否匹配
            switch ($v[3]){
                case 1://只付货款
                    if (!$v[5] || !$v[7] || !$v[8] || !$v[9] || !$v[10] || !$v[14] || !$v[16] || !$v[18] || !$v[19]){
                        echo '第'.$k.'条记录中，打款方式为只付货款，请填写购买时商品实际价格、买家实际支付、买家下单币种、公司刷单成本，公司成本对人民币汇率、为买家付款方式、买家收款账户、应付刷单费、买家收款币种、买家收款币种对人民币汇率等信息！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }
                    $back_his = $this->MTaskOperate->getAll(['order_no' => $v[2],'task_id' => $v[0],'operator_id' => $operator_id,'payment_type' =>[1,2,3,4,5,6,7,8,9],'status <>' => 4]);
                    if ($back_his){
                        var_export($back_his);
                        echo '第'.$k.'条记录与系统已有测评记录打款类型冲突，请检查后重新录入！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }
                    $obj->true_product_price = $v[5];
                    $obj->buyer_pay_total = $v[7];
                    $obj->buyer_pay_coin_type = $v[8];
                    $obj->true_company_cost = $v[9];
                    $obj->true_company_cost_rate = $v[10];
                    $obj->pay_account = $v[14];
                    $obj->true_shuadan_amount = $v[16];
                    $obj->coin_type = $v[18];
                    $obj->rate_rmb = $v[19];
                    break;
                case 2://付货款+一半佣金（买手要求付货款和一半佣金后，才愿意去评论）
                    if (!$v[5] || !$v[7] || !$v[8] || !$v[9] || !$v[10] || !$v[14] || !$v[16] || !$v[17] || !$v[18] || !$v[19]){
                        echo '第'.$k.'条记录中，打款方式为只付货款+一半佣金（买手要求付货款和一半佣金后，才愿意去评论），请填写购买时商品价格、买家实际支付、买家下单币种、公司刷单成本，公司成本对人民币汇率、为买家付款方式、买家收款账户、应付刷单费、买家佣金、买家收款币种、买家收款币种对人民币汇率等信息！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }
                    $back_his = $this->MTaskOperate->getAll(['order_no' => $v[2],'task_id' => $v[0],'operator_id' => $operator_id,'payment_type' =>[1,2,3,4,5,6,7,8,9],'status <>' => 4]);
                    if ($back_his){
                        echo '第'.$k.'条记录条记录与系统已有测评记录打款类型冲突，请检查后重新录入！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }

                    $obj->true_product_price = $v[5];
                    $obj->buyer_pay_total = $v[7];
                    $obj->buyer_pay_coin_type = $v[8];
                    $obj->true_company_cost = $v[9];
                    $obj->true_company_cost_rate = $v[10];
                    $obj->pay_account = $v[14];
                    $obj->true_shuadan_amount = $v[16];
                    $obj->coin_type = $v[18];
                    $obj->rate_rmb = $v[19];
                    $obj->commission = $v[17];
                    break;
                case 3://付佣金，（对应1已付货款，买手已测评过来找测评付全部佣金）
                    if (!$v[14] || !$v[17] || !$v[18] || !$v[19]){
                        echo '第'.$k.'条记录中，打款方式为付佣金，（对应1已付货款，买手已测评过来找测评付全部佣金），请填写为买家付款方式、买家收款账户、买家佣金、买家收款币种、买家收款币种对人民币汇率等信息！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }
                    $back_his = $this->MTaskOperate->getAll(['order_no' => $v[2],'task_id' => $v[0],'operator_id' => $operator_id,'payment_type' =>[2,3,4,5,6,8,9],'status <>' => 4]);
                    if ($back_his){
                        echo '第'.$k.'条记录条记录与系统已有测评记录打款类型冲突，请检查后重新录入！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }

                    $obj->pay_account = $v[14];
                    $obj->coin_type = $v[18];
                    $obj->rate_rmb = $v[19];
                    $obj->commission = $v[17];

                    break;
                case 4://付剩余一半佣金（对应2已付货款+一半佣金，买手完成测评后，把剩余佣金支付的申请）
                    if (!$v[14] || !$v[17] || !$v[18] || !$v[19]){
                        echo '第'.$k.'条记录中，打款方式为付剩余一半佣金（对应2已付货款+一半佣金，买手完成测评后，把剩余佣金支付的申请），请填写为买家付款方式、买家收款账户、买家佣金、买家收款币种、买家收款币种对人民币汇率等信息！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }
                    $back_his = $this->MTaskOperate->getAll(['order_no' => $v[2],'task_id' => $v[0],'operator_id' => $operator_id,'payment_type' =>[3,4,5,6,8],'status <>' => 4]);
                    if ($back_his){
                        echo '第'.$k.'条记录条记录与系统已有测评记录打款类型冲突，请检查后重新录入！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }

                    $obj->pay_account = $v[14];
                    $obj->coin_type = $v[18];
                    $obj->rate_rmb = $v[19];
                    $obj->commission = $v[17];

                    break;
                case 5://付货款+佣金（买手完成下单并完成测评之后才来联系测评要钱的申请）
                    if (!$v[5] || !$v[7] || !$v[8] || !$v[9] || !$v[10] || !$v[14] || !$v[16] || !$v[17] || !$v[18] || !$v[19]){
                        echo '第'.$k.'条记录中，打款方式为付货款+佣金（买手完成下单并完成测评之后才来联系测评要钱的申请），请填写购买时商品价格、买家实际支付、买家下单币种、公司刷单成本，公司成本对人民币汇率、为买家付款方式、买家收款账户、应付刷单费、买家佣金、买家收款币种、买家收款币种对人民币汇率等信息！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }
                    $back_his = $this->MTaskOperate->getAll(['order_no' => $v[2],'task_id' => $v[0],'operator_id' => $operator_id,'payment_type' =>[1,2,3,4,5,6,7,8,9],'status <>' => 4]);
                    if ($back_his){
                        echo '第'.$k.'条记录条记录与系统已有测评记录打款类型冲突，请检查后重新录入！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }
                    $obj->true_product_price = $v[5];
                    $obj->buyer_pay_total = $v[7];
                    $obj->buyer_pay_coin_type = $v[8];
                    $obj->true_company_cost = $v[9];
                    $obj->true_company_cost_rate = $v[10];
                    $obj->pay_account = $v[14];
                    $obj->true_shuadan_amount = $v[16];
                    $obj->coin_type = $v[18];
                    $obj->rate_rmb = $v[19];
                    $obj->commission = $v[17];

                    break;

                case 6://付货款+佣金+中介费（中介联系的买手完成全部流程后一次性支付所有费用）
                    if (!$v[5] || !$v[7] || !$v[8] || !$v[9] || !$v[10] || !$v[14] || !$v[16] || !$v[17] || !$v[18] || !$v[19] ||!$v[20] || !$v[22] || !$v[23] || !$v[24]){
                        echo '第'.$k.'条记录中，打款方式为付货款+佣金+中介费（中介联系的买手完成全部流程后一次性支付所有费用），请填写购买时商品价格、买家实际支付、买家下单币种、公司刷单成本，公司成本对人民币汇率、为买家付款方式、买家收款账户、应付刷单费、买家佣金、买家收款币种、买家收款币种对人民币汇率、中介收款账户、中介费、中介费对人民币汇率等信息！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }
                    $back_his = $this->MTaskOperate->getAll(['order_no' => $v[2],'task_id' => $v[0],'operator_id' => $operator_id,'payment_type' =>[1,2,3,4,5,6,7,8,9],'status <>' => 4]);
                    if ($back_his){
                        echo '第'.$k.'条记录条记录与系统已有测评记录打款类型冲突，请检查后重新录入！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }

                    $obj->true_product_price = $v[5];
                    $obj->buyer_pay_total = $v[7];
                    $obj->buyer_pay_coin_type = $v[8];
                    $obj->true_company_cost = $v[9];
                    $obj->true_company_cost_rate = $v[10];
                    $obj->pay_account = $v[14];
                    $obj->true_shuadan_amount = $v[16];
                    $obj->coin_type = $v[18];
                    $obj->rate_rmb = $v[19];
                    $obj->commission = $v[17];
                    $obj->intror_commission = $v[22];
                    $obj->intror_coin_type = $v[23];
                    $obj->intror_pay_account = $v[20];
                    $obj->intror_rate_rmb = $v[24];
                    break;

                case 7://付中介费（完成流程后，未付中介费的，另外生成付中介费）
                    if (!$v[20] || !$v[22] || !$v[23] || !$v[24]){
                        echo '第'.$k.'条记录中，打款方式为付中介费（完成流程后，未付中介费的，另外生成付中介费），请填写中介收款账户、中介费、中介费对人民币汇率等信息！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }
                    $back_his = $this->MTaskOperate->getAll(['order_no' => $v[2],'task_id' => $v[0],'operator_id' => $operator_id,'payment_type' =>[6,7,8,9],'status <>' => 4]);
                    if ($back_his){
                        echo '第'.$k.'条记录条记录与系统已有测评记录打款类型冲突，请检查后重新录入！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }

                    $obj->intror_commission = $v[22];
                    $obj->intror_coin_type = $v[23];
                    $obj->intror_pay_account = $v[20];
                    $obj->intror_rate_rmb = $v[24];
                    break;

                case 8://付佣金+中介费（对应1已付货款，中介介绍买手付全部佣金+中介费的申请）
                    if (!$v[14] ||  !$v[17] || !$v[18] || !$v[19] ||!$v[20] || !$v[22] || !$v[23] || !$v[24]){
                        echo '第'.$k.'条记录中，打款方式为付佣金+中介费（对应1已付货款，中介介绍买手付全部佣金+中介费的申请），请填写为买家付款方式、买家收款账户、买家佣金、买家收款币种、买家收款币种对人民币汇率、中介收款账户、中介费、中介费对人民币汇率等信息等信息！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }
                    $back_his = $this->MTaskOperate->getAll(['order_no' => $v[2],'task_id' => $v[0],'operator_id' => $operator_id,'payment_type' => [2,3,4,5,6,7,8,9],'status <>' => 4]);
                    if ($back_his){
                        echo '第'.$k.'条记录条记录与系统已有测评记录打款类型冲突，请检查后重新录入！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }
                    $obj->pay_account = $v[14];
                    $obj->coin_type = $v[18];
                    $obj->rate_rmb = $v[19];
                    $obj->commission = $v[17];
                    $obj->intror_commission = $v[22];
                    $obj->intror_coin_type = $v[23];
                    $obj->intror_pay_account = $v[20];
                    $obj->intror_rate_rmb = $v[24];
                    break;
                case 9://付一半佣金+中介费（对应2已付货款+一半佣金，中介介绍的买手付剩余佣金+中介费的申请 ）
                    if (!$v[14] ||  !$v[17] || !$v[18] || !$v[19] ||!$v[20] || !$v[22] || !$v[23] || !$v[24]){
                        echo '第'.$k.'条记录中，打款方式为付一半佣金+中介费（对应2已付货款+一半佣金，中介介绍的买手付剩余佣金+中介费的申请 ），请填写为买家付款方式、买家收款账户、买家佣金、买家收款币种、买家收款币种对人民币汇率、中介收款账户、中介费、中介费对人民币汇率等信息等信息！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }
                    $back_his = $this->MTaskOperate->getAll(['order_no' => $v[2],'task_id' => $v[0],'operator_id' => $operator_id,'payment_type' =>[3,4,5,6,7,8,9],'status <>' => 4]);
                    if ($back_his){
                        echo '第'.$k.'条记录条记录与系统已有测评记录打款类型冲突，请检查后重新录入！';
                        echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff6120" onclick="javascript:history.go(-1)">返回</button>';
                        exit();
                    }
                    $obj->pay_account = $v[14];
                    $obj->coin_type = $v[18];
                    $obj->rate_rmb = $v[19];
                    $obj->commission = $v[17];
                    $obj->intror_commission = $v[22];
                    $obj->intror_coin_type = $v[23];
                    $obj->intror_pay_account = $v[20];
                    $obj->intror_rate_rmb = $v[24];
                    break;
            }
            foreach ($obj as $o_k => $o_v){
                if ($o_v === true){
                    $obj->$o_k = '';
                }
            }

            if ($this->MTaskOperate->add($obj)) {
                // 添加成功更新已录测评数量
                $this->load->model('MTaskApplyNum');
                if ($this->MTaskApplyNum->updateCepingCount($obj->task_id, $obj->operator_id) === FALSE) {
                    $this->db->_trans_status = FALSE;
                }
                //更新task表中测评/销量数
                if ($this->MTask->updateCepingCount($obj->task_id) === FALSE) {
                    $this->db->_trans_status = FALSE;
                }
            }
        }
        if ($this->db->_trans_status){
            $this->db->trans_complete();

            echo '本次共导入测评记录'.count($new).'条，导入成功！';
            echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #3dff3f" onclick="javascript:history.go(-1)">返回</button>';
            exit();
        }else{
            echo '未能更新测评完成数量，请稍后重试！';
            echo '<button style="color: white;font-size:13px;font-weight:bold;padding: 4px 8px;background: #ff8e18" onclick="javascript:history.go(-1)">返回</button>';
            exit();
        }

    }
}
